{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Deep Learning Models -- A collection of various deep learning architectures, models, and tips for TensorFlow and PyTorch in Jupyter Notebooks.\n",
    "- Author: Sebastian Raschka\n",
    "- GitHub Repository: https://github.com/rasbt/deeplearning-models"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Sebastian Raschka \n",
      "\n",
      "CPython 3.6.1\n",
      "IPython 6.0.0\n",
      "\n",
      "tensorflow 1.2.0\n"
     ]
    }
   ],
   "source": [
    "%load_ext watermark\n",
    "%watermark -a 'Sebastian Raschka' -v -p tensorflow"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Model Zoo -- Softmax Regression"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Implementation of softmax regression (multinomial logistic regression)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting ./train-images-idx3-ubyte.gz\n",
      "Extracting ./train-labels-idx1-ubyte.gz\n",
      "Extracting ./t10k-images-idx3-ubyte.gz\n",
      "Extracting ./t10k-labels-idx1-ubyte.gz\n",
      "Epoch: 001 | AvgCost: 0.476 | Train/Valid ACC: 0.903/0.909\n",
      "Epoch: 002 | AvgCost: 0.339 | Train/Valid ACC: 0.911/0.918\n",
      "Epoch: 003 | AvgCost: 0.320 | Train/Valid ACC: 0.915/0.922\n",
      "Epoch: 004 | AvgCost: 0.309 | Train/Valid ACC: 0.918/0.923\n",
      "Epoch: 005 | AvgCost: 0.301 | Train/Valid ACC: 0.918/0.922\n",
      "Epoch: 006 | AvgCost: 0.296 | Train/Valid ACC: 0.919/0.922\n",
      "Epoch: 007 | AvgCost: 0.291 | Train/Valid ACC: 0.921/0.925\n",
      "Epoch: 008 | AvgCost: 0.287 | Train/Valid ACC: 0.922/0.925\n",
      "Epoch: 009 | AvgCost: 0.286 | Train/Valid ACC: 0.922/0.926\n",
      "Epoch: 010 | AvgCost: 0.283 | Train/Valid ACC: 0.923/0.926\n",
      "Epoch: 011 | AvgCost: 0.282 | Train/Valid ACC: 0.923/0.924\n",
      "Epoch: 012 | AvgCost: 0.278 | Train/Valid ACC: 0.925/0.927\n",
      "Epoch: 013 | AvgCost: 0.278 | Train/Valid ACC: 0.925/0.928\n",
      "Epoch: 014 | AvgCost: 0.276 | Train/Valid ACC: 0.925/0.925\n",
      "Epoch: 015 | AvgCost: 0.276 | Train/Valid ACC: 0.926/0.928\n",
      "Epoch: 016 | AvgCost: 0.274 | Train/Valid ACC: 0.927/0.927\n",
      "Epoch: 017 | AvgCost: 0.270 | Train/Valid ACC: 0.927/0.925\n",
      "Epoch: 018 | AvgCost: 0.273 | Train/Valid ACC: 0.927/0.930\n",
      "Epoch: 019 | AvgCost: 0.270 | Train/Valid ACC: 0.927/0.929\n",
      "Epoch: 020 | AvgCost: 0.268 | Train/Valid ACC: 0.927/0.927\n",
      "Epoch: 021 | AvgCost: 0.268 | Train/Valid ACC: 0.927/0.926\n",
      "Epoch: 022 | AvgCost: 0.270 | Train/Valid ACC: 0.928/0.926\n",
      "Epoch: 023 | AvgCost: 0.268 | Train/Valid ACC: 0.927/0.926\n",
      "Epoch: 024 | AvgCost: 0.266 | Train/Valid ACC: 0.929/0.926\n",
      "Epoch: 025 | AvgCost: 0.261 | Train/Valid ACC: 0.927/0.926\n",
      "Epoch: 026 | AvgCost: 0.269 | Train/Valid ACC: 0.929/0.927\n",
      "Epoch: 027 | AvgCost: 0.265 | Train/Valid ACC: 0.928/0.928\n",
      "Epoch: 028 | AvgCost: 0.261 | Train/Valid ACC: 0.929/0.928\n",
      "Epoch: 029 | AvgCost: 0.266 | Train/Valid ACC: 0.930/0.926\n",
      "Epoch: 030 | AvgCost: 0.261 | Train/Valid ACC: 0.929/0.924\n",
      "Test ACC: 0.925\n"
     ]
    }
   ],
   "source": [
    "import tensorflow as tf\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "\n",
    "\n",
    "##########################\n",
    "### DATASET\n",
    "##########################\n",
    "\n",
    "mnist = input_data.read_data_sets(\"./\", one_hot=True)\n",
    "\n",
    "\n",
    "##########################\n",
    "### SETTINGS\n",
    "##########################\n",
    "\n",
    "# Hyperparameters\n",
    "learning_rate = 0.5\n",
    "training_epochs = 30\n",
    "batch_size = 256\n",
    "\n",
    "# Architecture\n",
    "n_features = 784\n",
    "n_classes = 10\n",
    "\n",
    "\n",
    "##########################\n",
    "### GRAPH DEFINITION\n",
    "##########################\n",
    "\n",
    "g = tf.Graph()\n",
    "with g.as_default():\n",
    "\n",
    "    # Input data\n",
    "    tf_x = tf.placeholder(tf.float32, [None, n_features])\n",
    "    tf_y = tf.placeholder(tf.float32, [None, n_classes])\n",
    "\n",
    "    # Model parameters\n",
    "    params = {\n",
    "        'weights': tf.Variable(tf.zeros(shape=[n_features, n_classes],\n",
    "                                               dtype=tf.float32), name='weights'),\n",
    "        'bias': tf.Variable([[n_classes]], dtype=tf.float32, name='bias')}\n",
    "\n",
    "    # Softmax regression\n",
    "    linear = tf.matmul(tf_x, params['weights']) + params['bias']\n",
    "    pred_proba = tf.nn.softmax(linear, name='predict_probas')\n",
    "    \n",
    "    # Loss and optimizer\n",
    "    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(\n",
    "        logits=linear, labels=tf_y), name='cost')\n",
    "    optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)\n",
    "    train = optimizer.minimize(cost, name='train')\n",
    "\n",
    "    # Class prediction\n",
    "    pred_labels = tf.argmax(pred_proba, 1, name='predict_labels')\n",
    "    correct_prediction = tf.equal(tf.argmax(tf_y, 1), pred_labels)\n",
    "    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32), name='accuracy')\n",
    "\n",
    "    \n",
    "##########################\n",
    "### TRAINING & EVALUATION\n",
    "##########################\n",
    "\n",
    "with tf.Session(graph=g) as sess:\n",
    "    sess.run(tf.global_variables_initializer())\n",
    "\n",
    "    for epoch in range(training_epochs):\n",
    "        avg_cost = 0.\n",
    "        total_batch = mnist.train.num_examples // batch_size\n",
    "\n",
    "        for i in range(total_batch):\n",
    "            batch_x, batch_y = mnist.train.next_batch(batch_size)\n",
    "            _, c = sess.run(['train', 'cost:0'], feed_dict={tf_x: batch_x,\n",
    "                                                            tf_y: batch_y})\n",
    "            avg_cost += c\n",
    "        \n",
    "        train_acc = sess.run('accuracy:0', feed_dict={tf_x: mnist.train.images,\n",
    "                                                      tf_y: mnist.train.labels})\n",
    "        valid_acc = sess.run('accuracy:0', feed_dict={tf_x: mnist.validation.images,\n",
    "                                                      tf_y: mnist.validation.labels})  \n",
    "        \n",
    "        print(\"Epoch: %03d | AvgCost: %.3f\" % (epoch + 1, avg_cost / (i + 1)), end=\"\")\n",
    "        print(\" | Train/Valid ACC: %.3f/%.3f\" % (train_acc, valid_acc))\n",
    "        \n",
    "    test_acc = sess.run(accuracy, feed_dict={tf_x: mnist.test.images,\n",
    "                                             tf_y: mnist.test.labels})\n",
    "    print('Test ACC: %.3f' % test_acc)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
